package com.zl.cms.web;

import com.zl.cms.exception.CmsException;
import com.zl.cms.model.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Set;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-3-6 Time: 上午10:13
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
  @Override
  @SuppressWarnings("unchecked")
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    HttpSession session = request.getSession();
	  // 没有登录的话重新登录
	  String sid = request.getParameter("sid");
	  if(null !=sid && !"".equals(sid.trim())){
		  //当sid有值表示通过uploadify传递过来的，此时获取原有的session
		  session = CmsSessionContext.getSession(sid);
	  }
    HandlerMethod hm = (HandlerMethod) handler;
    System.out.println(hm.getBean().getClass().getName() + "." + hm.getMethod().getName());
    User user = (User) session.getAttribute("loginUser");

    if (null == user) {
      response.sendRedirect(request.getContextPath() + "/login");
    } else {
      boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
      if (!isAdmin) {
        // 不是超级管理员,判断是否有权限访问
        Set<String> actions = (Set<String>) session.getAttribute("allActions");
        String actionName = hm.getBean().getClass().getName() + "." + hm.getMethod().getName();
        if (!actions.contains(actionName)) {
          throw new CmsException("没有权限访问该功能");
        }
      }
    }
    return super.preHandle(request, response, handler);
  }
}
